/*
 * TransiCast City Visions
 * (c) 2014 Joachim Pfeiffer
 * www.transicast.com
 */
package com.transicast.cityvisions;

import java.util.concurrent.ConcurrentHashMap;

import android.util.Log;

import com.metaio.sdk.jni.IGeometry;
import com.metaio.sdk.jni.IMetaioSDKAndroid;

public class BusesPool {
	private static final int							POOL_SIZE = 80;
	private int											mPoolOccupation;
	private ConcurrentHashMap<String, IGeometry> 		mPool;

	public void cleanup(ConcurrentHashMap<String, Arrival> arrivals) {
		if (arrivals == null)
			return;
		for (String block : mPool.keySet()) {
			if (arrivals.containsKey(block))
				continue;
			IGeometry bus = mPool.get(block);
			if (bus == null || !bus.isVisible())
				continue;
			bus.setVisible(false);
			mPool.remove(block);
			if (mPoolOccupation > 0)
				mPoolOccupation--;
			else
				Log.v("TransiCastCityVisions", "Buses pool occupancy violation: " + mPoolOccupation);
			mPool.put("-" + mPoolOccupation, bus);
		}
	}

	public IGeometry getBus(String hash) {
		if (mPool == null || hash == null)
			return null;
		IGeometry bus = mPool.get(hash);
		if (bus != null)
			return bus;
		if (!(mPoolOccupation < POOL_SIZE))
			return null;
		String freeEntryHash = "-" + mPoolOccupation;
		bus = mPool.get(freeEntryHash);
		mPool.remove(freeEntryHash);
		mPool.put(hash, bus);
		bus.setVisible(true);
		mPoolOccupation++;
		return bus;
	}

	public BusesPool(IMetaioSDKAndroid metaioSDK, String[] models) {
		mPool = new ConcurrentHashMap<String, IGeometry>();
		for (int i = 0; i < POOL_SIZE; i++) {
			int j = Utilities.random(0, models.length - 1);
			IGeometry bus = metaioSDK.createGeometry(models[j]);
			bus.setVisible(false);
			mPool.put("-" + i, bus);
			bus.setScale(ARView.BASE_SCALE);
		}
		mPoolOccupation = 0;
	}
}
